package com.kgis.fm.business.view
{
	import com.kgis.fm.business.event.FmMetaDataEvent;
	import com.kgis.fm.business.view.MapView;
	import com.kgis.fm.common.component.legend.FmLegendControl;
	import com.kgis.fm.common.manager.BusinessLayerManager;
	import com.kgis.fm.common.manager.BusinessLegendTreeManager;
	import com.kgis.fm.common.manager.MetaDataManager;
	import com.kgis.fm.flex.model.constant.LayerTypeConstant;
	import com.kgis.fm.flex.model.manager.FmMetaData;
	import com.kgis.fm.flex.model.metadata.MapExtent;
	import com.kgis.fm.flex.model.term.LayerParameter;
	import com.kgis.map.Map;
	import com.kgis.map.geometry.basetype.Extent;
	import com.kgis.map.geometry.basetype.Location;
	import com.kgis.map.handler.IHandler;
	import com.kgis.map.handler.feature.draw.DrawHandler;
	import com.kgis.map.layer.TMS;
	import com.kgis.map.projection.Projection;
	import com.kgis.mvc.CommandCompletionEvent;
	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;

	[Event(name="{com.kgis.fm.business.event.FmMetaDataEvent.REQUEST_ID}", type="com.kgis.fm.business.event.FmMetaDataEvent")]
	public class MapViewMediator extends EventDispatcher
	{
		private var kgisMap:Map=null;
		[Bindable]
		private var _symbolDic:Dictionary=null;
		private var handler:IHandler;
		private var pointHandler:DrawHandler;
		private var lineHandler:DrawHandler;
		private var polygonHandler:DrawHandler;

		[Bindable]
		private var _maxExtentInitial:Extent; //真实地图范围
		[Bindable]
		private var _maxExtentCalculate:Extent; //根据全球算出来的范围   对于除WGS84外的其他坐标系与真实地图范围一致

		[Bindable]
		private var _maxExtentArray:Array;
		[Bindable]
		private var _maxResolution:Number;

		private var _view:MapView;
		public var _layerItemArray:ArrayCollection=new ArrayCollection;

		private var metaData:FmMetaData;

		private var distance:Number=0; //光路故障定位

		private var _ready:Boolean=false;

		[InjectableView]
		/**
		 * The mediator's view.
		 */
		public function get view():MapView
		{
			return _view;
		}

		public function set view(value:MapView):void
		{
			_view=value;
			dispatchEvent(new FmMetaDataEvent(FmMetaDataEvent.TYPE_GET_FMMETADATA));
		}

		[ResponseHandler("{com.kgis.fm.business.event.FmMetaDataEvent.RETURN_ID}")]
		public function onFmMetaDataEvent(event:CommandCompletionEvent):void
		{
			if (event.error)
			{
				Alert.show(event.error.message);
				return;
			}
			var request:FmMetaDataEvent=event.request as FmMetaDataEvent;

			if (request.actionType == FmMetaDataEvent.TYPE_GET_FMMETADATA)
			{
				var metaData:FmMetaData=event.result as FmMetaData;
				if (!_ready)
				{
					_ready=true;
					MetaDataManager.getInstance().addMetaData(MetaDataManager.KEY_KGM_METAData, metaData);
				}
				LoadSymbolSwf();
			}
		}

		private function LoadSymbolSwf():void
		{
			var loader:Loader=new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			var request:URLRequest=new URLRequest("mapsymbol.swf");
			var context:LoaderContext=new LoaderContext();
			context.checkPolicyFile=false;
			context.applicationDomain=ApplicationDomain.currentDomain;
			loader.load(request, context);
		}

		private function completeHandler(event:Event):void
		{
			var loader:LoaderInfo=event.target as LoaderInfo;

			var pointSymbolDic:Dictionary=new Dictionary();

			for (var i:int=1; i <= 200; i++)
			{
				var symbolName:String=i.toString();
				if (i < 10)
				{
					symbolName="s00" + symbolName;
				}
				else if (i < 100)
				{
					symbolName="s0" + symbolName;
				}
				else
				{
					symbolName="s" + symbolName;
				}
				var wrapperClass:Class=loader.applicationDomain.getDefinition(symbolName) as Class;
				pointSymbolDic[symbolName]=wrapperClass;
			}
			this._symbolDic=pointSymbolDic;
			initMap();
		}

		private function ioErrorHandler(event:IOErrorEvent):void
		{
			Alert.show("加载swf矢量符号出错！", "错误提示框");
		}

		private function initMap():void
		{
			if (kgisMap != null)
			{
				return;
			}
			metaData=MetaDataManager.getInstance().getMetaData(MetaDataManager.KEY_KGM_METAData) as FmMetaData;
			var mapExtents:ArrayCollection=metaData.mapExtentList as ArrayCollection;

			if (mapExtents.length > 0)
			{
				var tmpMapExtent:MapExtent=mapExtents[0] as MapExtent;
				_maxExtentInitial=new Extent(tmpMapExtent.xmin, tmpMapExtent.ymin, tmpMapExtent.xmax, tmpMapExtent.ymax);
				_maxExtentCalculate=new Extent(tmpMapExtent.xmin, tmpMapExtent.ymin, tmpMapExtent.xmax, tmpMapExtent.ymax);
//				_view.mapControl.map.projection=new Projection("BEIJING54");
				if (tmpMapExtent.srsCode) {
					_view.mapControl.map.projection = new Projection(tmpMapExtent.srsCode);
				}
			}else {
				_maxExtentInitial = new Extent(-180, -90, 180, 90);
				_maxExtentCalculate = new Extent(-180, -90, 180, 90);
				_view.mapControl.map.projection = new Projection("EPSG:4326");
			}
			
			initBaseMap();
			_view.mapControl.initMap();
			kgisMap.moveTo(this._maxExtentInitial.center, 1);

		}

		private function initBaseMap():void
		{
			kgisMap=_view.mapControl.map;
			kgisMap.symbolDic=this._symbolDic;
			var tileLayer:LayerParameter=MetaDataManager.getLayerParameterByType(LayerTypeConstant.LAYERTYPE_TILE);
			if (tileLayer)
			{
				var baseLayerType:int=tileLayer.layerType;
				_view.mapControl.maxExtent=[_maxExtentCalculate.xmin, _maxExtentCalculate.ymin, _maxExtentCalculate.xmax, _maxExtentCalculate.ymax];
				_view.mapControl.maxResolution=(_maxExtentCalculate.xmax - _maxExtentCalculate.xmin) / 256;
				var tms:TMS=new TMS(0, "Tms", tileLayer.layerTable);
				tms.tileOrigin=new Location(this._maxExtentCalculate.xmin, this._maxExtentCalculate.ymax);
				kgisMap.addLayer(tms);
			}
			BusinessLayerManager.initFeatureLayerByMetaData(_view.legendId, kgisMap);
			BusinessLegendTreeManager.initLegendTree(_view.legendId, kgisMap);
			
		
		}

	}
}